define(
	[
		'require'
	],
	function(require){
		var Controller = Ember.Controller.extend({
			needs: ["configAgreement"],
			form: {
				"ip": "",
				"port": "1108",
				"name": "",
				"remarks": "",
				"policys": "DROP", /*包过滤 form值*/
				'glopolicy': "DROP",
				"sourceIp": "",
				"sourceIp1": "",
				"sourcePort": "",
				"sourcePort1": "",
				"dstIp": "",
				"dstIp1" : "",
				"dstPort" : "",
				"dstPort1": "",
				"mac" : "",
				"policyName": "",
				"confType": "4",
				"analyzerId": ""
			},
			init: function(){
				this.requireAgreementList();
				this._super();
			},
			/*
				协议分析器方法
			 */
			defaultpolicys : Ember.A([{
				"displaytext" : "接收",
				"value" : "ACCEPT"
			}, {
				"displaytext" : "丢弃",
				"value" : "DROP"
			} ]),

			policyRules: Ember.A(),
			isFilterClose: false, // 包过滤弹框关闭


			/*
				列配置
			*/
			agreementColumns: [
				{
					headerText: "IP",
					dataKey:"ip",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.ip;
							if(!data){
								data = "-";
							}
							var cb = $("<div class='com-agreement'></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "端口",
					dataKey:"port",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.port;
							if(!data){
								data = "-";
							}
							var cb = $("<div class='com-agreement'></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "备注",
					dataKey:"memo",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller");
							var data = args.row.data.memo;
							if(!data){
								data = "无";
							}
							var cb = $("<div class='com-agreement'></div>").text(data);
							cb.appendTo(args.$container);
							return true;
						}
					}
				},
				{
					headerText: "操作",
					dataKey:"operation",
					textAlignment:"left",
					cellFormatter:function(args){
						if (args.row.type & $.wijmo.wijgrid.rowType.data) {
							var ctrl = this.get("controller"),
								data = args.row.data,
								$btnGroup = $("<div class='com-agreement'></div>").appendTo(args.$container);
								var cb = $('<button class="u-btn-blue mr5" type="button" title="重新加载">重新加载</button>');
				
							cb.appendTo($btnGroup).on("click",function(){
								ctrl.reloadAgreementItem(data.id);
							});		

							var lb = $('<button class="u-btn-blue mr5" type="button" title="协议分析器日志">查看日志</button>');
				
							lb.appendTo($btnGroup).on("click",function(){
								var dialog = Broada.getView("configAgreementLog");
								ctrl.dialogAgreementItem(data.id).then(function(response){
									var logs = response.logs;
									logs.forEach(function(node){
										var date = new Date(node.callTime);
										var dateFor = APM.util.formatDate(date, "yyyy-MM-dd H:mm:ss");
										Ember.set(node, "callTime", dateFor);
									});

									logs.forEach(function(node){
										switch (node.status) {
											case 1: node.status = "安装成功";break;
											case 2: node.status = "安装失败";break;
											case 3: node.status = "启用成功";break;
											case 4: node.status = "启用失败";break;
											case 5: node.status = "禁用成功";break;
											case 6: node.status = "禁用失败";break;
										}
									});

									ctrl.set("agreementLogs",Ember.A(logs));
								});
								
								dialog.openDialog();
								
							});	

							var ab = $('<button class="u-btn-blue mr5" type="button" title="数据包过滤规则">包过滤</button>');
							ab.appendTo($btnGroup).on("click",function(e){
								ctrl.set("form.analyzerId",data.id);
								//ctrl.transitionToRoute("config.packetfilterface",data.id);return;
								ctrl.store.ajax("GET", "analyzers/"+data.id+"/filters",{
									configItem:"filter"
								}).then(function(response) {
					
									var result = response.result;
									var dict = {"DROP": "丢弃", "ACCEPT": "接收"}
									result.forEach(function(node){

										if(node.policys == "DROP"){
											Ember.set(node,"policyName","丢弃")
										}else{
											Ember.set(node,"policyName","接收")
										}
									});
									
									ctrl.set("policyRules", Ember.A(result));
								});

								var $dataFilter = $("#dataPackageFilterInfo");
								$dataFilter.removeClass("bounceOutRight animated hide");
								$dataFilter.addClass("bounceInRight animated");
								e.stopPropagation();

								// 包过滤规则出现时候的弹框消失处理
								$(document).on("click",function(e){
									if(!$dataFilter.length){
										return;
									}
									var $target = $(e.target);
									var isClose = $target.hasClass("dataFilter")
												  || $target.parents(".dataFilter").length
												  || $(".ui-dialog-overlay").length
												  || $target.parents(".broada-ui-message").length
												  || $target.parents(".ui-dialog").length;

									if(!isClose){
										$dataFilter.removeClass("bounceInRight animated");
										$dataFilter.addClass("bounceOutRight animated hide");
									}
								});

							});


							var ub = $('<button class="u-btn-danger" title="删除">删除</button>');

							ub.appendTo($btnGroup).on("click",function(){
								confirmDialog("确定删除该协议分析器？").then(function(){
									ctrl.delAgreementItem(data.id)
								});	
							});	

							return true;
						}
					}
				}
			],

			dialogAgreementItem: function(id){
				var ctrl = this;
				return this.store.ajax("GET","analyzers/"+id).then(function(response){
					return response;
				});
			},

			reloadAgreementItem: function(id){
				var ctrl = this;
				return this.store.ajax("GET","analyzers/reload/"+id).then(function(response){
				});
			},

			requireAgreementList: function(){
				var ctrl = this;
				var params = {
					"pageIndex": this.get("pageIndex"),
				    "pageSize": this.get("pageSize")
				};
				return this.store.ajax("GET", "analyzers", params)
				.then(function(response){
					var result = response.result;
					ctrl.set("agreementList",result);
					return response;
				})
			},

			addAgreementItem: function(){
				var ctrl = this;
				var params = {
					"ip": this.get("form.ip"),
				    "port": this.get("form.port"),
				    "memo": this.get("form.memo")
				};

				return this.store.ajax("POST", "analyzers", params)
				.then(function(response){
					if(response){
						ctrl.set("formTip", response.message);
					}
					ctrl.requireAgreementList();
				})
			},
			delAgreementItem: function(id){
				var ctrl = this;

				return this.store.ajax("DELETE", "analyzers/"+id)
				.then(function(response){
					ctrl.requireAgreementList();
				})
			},

			agreementList: Ember.A([
				// {"remarks":"","port":"","ip":"","name":""}
			]),
			checkFormValid: function(){
					var form = this.get("form");
					
					this.set("formTip", null);
					this.set("saveResult", null);
					var ipReg1 =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;

					if(form.sourceIp){
						if(!ipReg1.test(form.sourceIp)){  
						   this.set("saveResult", "开始源IP地址范围非法，请重新输入!");
						   return false;
						}  
					}
					if(form.sourceIp1){
						if(!ipReg1.test(form.sourceIp1)){  
						   this.set("saveResult", "结束源IP地址范围非法，请重新输入!");
						   return false;
						}  
					}
					if(form.sourcePort){
						var reg = new RegExp("^[0-9]*$"); 
						var port=form.sourcePort;
						var port1=parseInt(form.sourcePort);
						if (!(reg.test(port) && port1<65536)) {
							this.set("saveResult", "开始源端口错误，请重新输入!");
							return false;
						} 
					}
					if(form.sourcePort1){
						var reg = new RegExp("^[0-9]*$"); 
						var port1=form.sourcePort1;
						var port=parseInt(form.sourcePort1);
						if (!(reg.test(port1) && port<65536)) { 
							this.set("saveResult", "结束源端口错误，请重新输入!");
							return false;
						} 
					}

					if(form.dstIp){
						if(!ipReg1.test(form.dstIp)){  
						   this.set("saveResult", "开始目的IP地址范围非法，请重新输入!");
						   return false;
						}  
					}
					if(form.dstIp1){
						if(!ipReg1.test(form.dstIp1)){  
						   this.set("saveResult", "结束目的IP地址范围非法，请重新输入!");
						   return false;
						}  
					}
					if(form.dstPort){
						var reg = new RegExp("^[0-9]*$"); 
						var port=form.dstPort;
						var port1=parseInt(form.dstPort);
						if (!(reg.test(port) && port1<65536)) {
							this.set("saveResult", "开始目的端口错误，请重新输入!");
							return false;
						} 
					}
					if(form.dstPort1){
						var reg = new RegExp("^[0-9]*$"); 
						var port1=form.dstPort1;
						var port=parseInt(form.dstPort1);
						if (!(reg.test(port1) && port<65536)) { 
							this.set("saveResult", "结束目的端口错误，请重新输入!");
							return false;
						} 
					}
					if(form.mac){
						var reg2=/[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}-[A-Fa-f0-9]{2}/;
						var reg3=/[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}:[A-Fa-f0-9]{2}/;
						if(!(reg2.test(form.mac) || reg3.test(form.mac))){  
							   this.set("saveResult", "Mac地址非法，请重新输入!");
							   return false;
						} 
					}
					
					if((form.dstIp && form.dstIp1) || (form.sourceIp1 && form.sourceIp)){
						var startIp=form.dstIp;
						var endIp=form.dstIp1;
						var startIp1=form.sourceIp;
						var endIp1=form.sourceIp1;
						if(startIp){
							var startIpint=parseInt(startIp.replace(/\d+\.?/ig,function(a){
								a = parseInt(a); 
								return (a > 15 ? "" : "0") + a.toString(16);
							}),16);
						};
						if(endIp){
							var endIpint=parseInt(endIp.replace(/\d+\.?/ig,function(b){
								b = parseInt(b); 
								return (b > 15 ? "" : "0") + b.toString(16);
							}),16);
						};
						if(startIp1){
							var startIpint1=parseInt(startIp1.replace(/\d+\.?/ig,function(a){
								a = parseInt(a); 
								return (a > 15 ? "" : "0") + a.toString(16);
							}),16);
						}
						if(endIp1){
							var endIpint1=parseInt(endIp1.replace(/\d+\.?/ig,function(b){
								b = parseInt(b); 
								return (b > 15 ? "" : "0") + b.toString(16);
							}),16);
						}
						if(startIpint && endIpint){
							if(startIpint>endIpint){
								 this.set("saveResult", "开始目的IP地址不应大于结束目的IP地址!");
									return false;
							}
						}
						if(startIpint && endIpint){
							if(startIpint == endIpint){
								 this.set("saveResult", "开始目的IP地址与结束目的IP地址相同!");
									return false;
							}
						}
						if(startIpint1 && endIpint1){
							if(startIpint1>endIpint1){
								 this.set("saveResult", "开始源IP地址不应大于结束源IP地址!");
									return false;
							}
						}
						if(startIpint1 && endIpint1){
							if(startIpint1 == endIpint1){
								 this.set("saveResult", "开始源IP地址与结束源IP地址相同!");
									return false;
							}
						}
					}
					
					if((form.dstPort && form.dstPort1) || (form.sourcePort && form.sourcePort1)){
						var startPort=parseInt(form.dstPort);
						var endPort=parseInt(form.dstPort1);
						var startPort1=parseInt(form.sourcePort);
						var endPort1=parseInt(form.sourcePort1);
						if(startPort>endPort){
							 this.set("saveResult", "开始目的端口不应大于结束目的端口!");
								return false;
						}
						if(startPort == endPort){
							 this.set("saveResult", "开始目的端口与结束目的端口相同!");
								return false;
						}
						if(startPort1>endPort1){
							 this.set("saveResult", "开始源端口不应大于目的结束源端口!");
								return false;
						}
						if(startPort1 == endPort1){
							 this.set("saveResult", "开始源端口与结束源端口相同!");
								return false;
						}
						
					}
					
					// if(!(form.dstIp||form.dstPort||form.mac||form.sourcePort||form.sourceIp)){
					// 	this.set("saveResult", "不能添加空策略!");
					// 	return false;
					// }
					this.set("saveResult", null);
					return true;
				},
			updatePolicy: function(){
				var ctrl = this,
					form = this.get("form"),
					policyRules = this.get('policyRules'),
					rulesArray = [];
				
				ctrl.set("saveResult", null);
				policyRules.forEach(function(item) {
					rulesArray.push({'sIp':item["sIp"],'sPort':item["sPort"],'dIp':item["dIp"],'dPort':item["dPort"],'policys':item["policys"]});
				});
				this.store.ajax("POST", "analyzers/filters/"+form.analyzerId, {
					defaultpolicy : form.glopolicy,
					policyRules:JSON.stringify(rulesArray),
					confType:form.confType
				}).then(function(response){
					//alertTip("保存成功！");
					var order = response.order;
					ctrl.get("policyRules").forEach(function(node,index) {
						node.id = order[index].id;
					});
				});
			},
			actions: {
				reset : function() {
					this.set("formTip", null);
					this.set("saveResult", null);
				},
				//对话框操作打开方法
				openDialog: function(){
					this.set("formTip", null);
					this.set("form.ip","");
					this.set("form.port","1108");
					this.set("form.remarks","");
					var dialog = Broada.getView("configAgreement_add");

          			Broada.getView("configAgreement_add").openDialog();
				},
				addAgreement: function(){
					var dialog = Broada.getView("configAgreement_add");
          			
					var form = this.get("form");
					this.set("formTip",null);
					// if(form.ip){
					// 	var reg1=/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
					// 	if(!reg1.test(form.ip)){  
					// 	   this.set("formTip", "IP地址不正确，请重新输入!");
					// 	   return false;
					// 	}  
					// }
					if(form.port){
						var reg = new RegExp("^[0-9]*$"); 
						var port=form.port;
						var port1=parseInt(form.port);
						if (!(reg.test(port) && port1<65536)) {
							this.set("formTip", "端口错误，请重新输入!");
							return false;
						} 
					}
					
					if(form.ip == ""){
						 this.set("formTip", "ip不能为空，请重新输入!");
						  return false;
					}
					if(form.port == ""){
						 this.set("formTip", "port不能为空，请重新输入!");
						  return false;
					}
					this.addAgreementItem().then(function(response){
						Broada.getView("configAgreement_add").closeDialog();
					});
				},
				closeDialog: function(){
					var dialog = Broada.getView("configAgreement_add");
					Broada.getView("configAgreement_add").closeDialog();
				},
				/*
					协议分析器action方法
				 */
				openDataFilterDialog: function(){
					this.set("formTip", null);
					this.set("saveResult", null);
					this.set("form.policys", "ACCEPT");
					var dialog = Broada.getView("packet_filter_add");
					dialog.openDialog();
				},
				closeDataFilterDialog: function(){
					this.set("saveResult", null);
					Broada.getView("packet_filter_add").closeDialog();
				},
				addPolicy : function() {
					if (!this.checkFormValid()) {
						return;
					}
					var policyRules = this.get("policyRules");
					var policyObj = {};
					var ctrl = this;
					var form = this.get("form");
					var ipstr="";
					var ip1str="";
					if (form.dstIp&&form.dstIp1) {
						 ipstr=form.dstIp+"-"+form.dstIp1;
					} else {
						if (form.dstIp) {
							 ipstr=form.dstIp;
						}

						if (form.dstIp1) {
							 ipstr=form.dstIp1;
						}
					};
					if (form.sourceIp&&form.sourceIp1) {
						 ip1str=form.sourceIp+"-"+form.sourceIp1;
					} else {
						if (form.sourceIp) {
							 ip1str=form.sourceIp;
						}

						if (form.sourceIp1) {
							 ips1tr=form.sourceIp1;
						}
					};
					var portstr="";
					if (form.dstPort&&form.dstPort1) {
						 portstr=form.dstPort+"-"+form.dstPort1;
					} else {
						if(form.dstPort){
							 portstr=form.dstPort;
						};
						if(form.dstPort1){
							 portstr=form.dstPort1;
						}
					}
					var port1str="";
					if (form.sourcePort&&form.sourcePort1) {
						 port1str=form.sourcePort+"-"+form.sourcePort1;
					} else {
						if(form.sourcePort){
							 port1str=form.sourcePort;
						};
						if(form.sourcePort1){
							 port1str=form.sourcePort1;
						}
					}
					var addId=1+policyRules.length;
					var dict = {"DROP": "丢弃","ACCEPT": "接收"};
					policyObj.dIp = ipstr;
					policyObj.sIp = ip1str;
					policyObj.id=addId;
					policyObj.dPort = portstr;
					policyObj.sPort = port1str;
					policyObj.mac = form.mac;
					policyObj.policys=form.policys;
					if(dict[policyObj.policys]){
						policyObj.policyName=dict[policyObj.policys];
					}
					policyRules.pushObject(Ember.A(policyObj));
					//ctrl.send("closeDialog");

					// 确定后保存
					this.store.ajax("POST","analyzers/filter",{
						"analyzerId": form.analyzerId,
						"srcFromIp": form.sourceIp,
						"srcToIp": form.sourceIp1,
						"srcFromPort": form.sourcePort,
						"srcToPort": form.sourcePort1,
						"dstFromIp": form.dstIp,
						"dstToIp": form.dstIp1,
						"dstFromPort": form.dstPort,
						"dstToPort": form.dstPort1,
						"policys": form.policys
					}).then(function(response){
						alertTip("保存成功！");
					});

					this.set("form.dstIp", "");
					this.set("form.dstIp1", "");
					this.set("form.dstPort", "");
					this.set("form.dstPort1", "");
					this.set("form.sourceIp", "");
					this.set("form.sourceIp1", "");
					this.set("form.sourcePort", "");
					this.set("form.sourcePort1", "");
					this.set("form.mac", "");
					this.set("policyName","");
					// ctrl.send("closeDialog");
					this.set("saveResult", "");
					this.set("form.policys", "ACCEPT");
					Broada.getView("packet_filter_add").closeDialog();

				},
				delPolicy : function() {
					var policyRules = this.get('policyRules');
					var checked = policyRules.filterProperty('checked', true);
					if (checked.length == 0) {
						alertDialog("请勾选要删除的策略!");
					}
					confirmDialog("确定删除所选过滤策略吗?").then(function(){
						policyRules.removeObjects(checked);
					});
				},
				save : function() {
					var ctrl = this,
						form = this.get("form"),
						policyRules = this.get('policyRules'),
						rulesArray = [];
					
					ctrl.set("saveResult", null);
					policyRules.forEach(function(item) {
						rulesArray.push({'sIp':item["sIp"],'sPort':item["sPort"],'dIp':item["dIp"],'dPort':item["dPort"],'policys':item["policys"]});
					});
					this.store.ajax("POST", "analyzers/filters/"+ctrl.get("model.id"), {
						defaultpolicy : form.glopolicy,
						policyRules:JSON.stringify(rulesArray),
						confType:form.confType
					}).then(function(response){
						alertTip("保存成功！");
					});
				},
				singleDelPolicy : function(policyRule) {
					this.set("isFilterClose",false);
					var policyRules = this.get('policyRules');
					var analyzerId = this.get("form").analyzerId;
					var id = policyRule.id;	
					var ctrl = this;
					confirmDialog("确定删除该过滤策略吗?").then(function(){
						// policyRules.removeObject(policyRule);
						ctrl.store.ajax("DELETE","analyzers/filters/"+analyzerId,{
							"id":id
						}).then(function(response){
							policyRules.removeObject(policyRule);
							alertTip("删除成功！");
						});
					});		
				},

				upPriority: function(policyRule){
					this.set("isFilterClose",false);
					var policyRules = this.get("policyRules"),
						index = policyRules.indexOf(policyRule);

					if(index != -1 && index > 0){
						policyRules.removeObject(policyRule);
						policyRules.insertAt(index-1, policyRule);
					}
					this.updatePolicy();
				},

				downPriority: function(policyRule){
					this.set("isFilterClose",false);
					var policyRules = this.get("policyRules"),
						len = policyRules.length,
						index = policyRules.indexOf(policyRule);

					if(index != -1 && len > 1 && index < len-1 ){
						policyRules.removeObject(policyRule);
						policyRules.insertAt(index+1, policyRule);
					}
					this.updatePolicy();
				}
			}
		});

		APM.ConfigAgreementController = Controller;
		return Controller;
	}
);